<template>
  <!-- 全屏加载状态 -->
  <div v-if="pageLoading" class="full-page-loading">
    <el-loading :fullscreen="true" text="商品信息加载中，请稍候..." />
  </div>
  
  <template v-else>
    <!-- 商铺卡片信息 -->
    <div class="shop-header">
    <div class="shop-header-left">
      <router-link v-if="shopId" :to="{
        name: 'ShopDetail',
        params: {
          id: shopId
        }
      }">
        <div class="shop-info">
          <img :src="shopInfo.image" class="shop-image" alt="店铺图片">
          <div class="shop-detail">
            <h3 class="shop-name">{{ shopInfo.name }}</h3>
            <div class="shop-score">
              <StarRating :score="shopInfo.score || 0" />
            </div>
          </div>
        </div>
      </router-link>
      <div v-else class="shop-info">
        <img :src="shopInfo.image" class="shop-image" alt="店铺图片">
        <div class="shop-detail">
          <h3 class="shop-name">{{ shopInfo.name }}</h3>
          <div class="shop-score">
            <StarRating :score="shopInfo.score || 0" />
          </div>
        </div>
      </div>
    </div>
    <div class="shop-header-right">
      <a href="#" class="contact-service">
        <i class="el-icon-service"></i>
        <span>联系客服</span>
      </a>
      <router-link v-if="shopId" :to="{
        name: 'ShopDetail',
        params: {
          id: shopId
        }
      }" class="enter-shop">
        <i class="el-icon-shop"></i>
        <span>进入店铺</span>
      </router-link>
      <a v-else class="enter-shop disabled">
        <i class="el-icon-shop"></i>
        <span>进入店铺</span>
      </a>
    </div>
    </div>
    <!-- 商品详情 -->
    <div class="goods-detail-container">
      <!-- 左侧图片区 -->
      <div class="goods-images">
        <img :src="currentImage" class="main-image" />
        <div class="sub-images">
          <img
            v-for="(img, idx) in spu.subImages"
            :key="idx"
            :src="img"
            :class="{ active: currentImage === img }"
            @click="currentImage = img"
          />
        </div>
      </div>

      <!-- 右侧信息和购买区 -->
      <div class="goods-right-section">
        <!-- 商品信息区 -->
        <div class="goods-info">
          <h1 class="title">{{ spu.title }}{{ spu.description }}</h1>
          <div class="brand-shop">
            <span>品牌：{{ brandName }}</span>
            <span>店铺：{{ shopName }}</span>
          </div>
          <div class="price">
            <span class="current-price">￥{{ spu.price }}</span>
            <span class="origin-price" v-if="sku.cost_price">￥{{ sku.cost_price }}</span>
          </div>
          <div class="promotion" v-if="promotionInfo">{{ promotionInfo }}</div>
          <div class="sales-stock">
            <span>销量：{{ sales }}</span>
            <span>库存：{{ sku.stock }}</span>
          </div>
          <!-- sku规格列表 -->
           <!-- specs名称 -->
           <div class="specs-name">
            <span>规格：</span>
            <span>{{ specTemplate.label }}</span>
           </div>
          <div class="specs">
            <div v-for="(options, key) in specOptions" :key="key" class="spec-row">
              <span class="spec-label">{{ key }}：</span>
              <span
                v-for="option in options"
                :key="option"
                :class="['spec-option', { selected: selectedSpecs[key] === option }]"
                @click="selectSpec(key, option)"
              >{{ option }}</span>
            </div>
          </div>
        </div>

        <!-- 购买区 -->
        <div class="goods-buy">
          <!-- 数量选择 -->
          <div class="quantity">
            <span>数量：</span>
            <div class="quantity-input">
              <el-input-number v-model="quantity" :min="1" :max="10" @input="validateQuantity"/>
            </div>
          </div>
          <div class="buy-btns">
            <button @click="handleAddToCart">加入购物车</button>
            <button class="buy-now" @click="buyNow">立即购买</button>
            <button
              class="favorite-btn"
              :class="{ active: isFavorite }"
              @click="handleFavorite"
            >
              <i :class="isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
              {{ isFavorite ? '已收藏' : '收藏' }}
            </button>
          </div>
          <div class="service">
            <span>正品保障</span>
            <span>极速退款</span>
            <span>七天无理由退换</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 用户评价 -->
    <div class="goods-comments">
      <h2 class="comments-title">用户评价</h2>
      
      <!-- 添加评论表单 -->
      <div class="comment-form-container" v-if="canComment">
        <h3 class="comment-form-title">发表评价</h3>
        <div class="comment-form">
          <div class="rating-row">
            <span class="form-label">评分：</span>
            <el-rate v-model="commentForm.rating" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
          </div>
          <div class="content-row">
            <span class="form-label">评价内容：</span>
            <el-input
              v-model="commentForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入您的评价内容..."
              maxlength="500"
              show-word-limit
            />
          </div>
          <div class="image-upload-row">
            <span class="form-label">上传图片：</span>
            <el-upload
              class="comment-image-upload"
              action="/api/upload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              :limit="5"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </div>
          <div class="comment-submit">
            <el-button type="primary" :loading="submitLoading" @click="submitComment">提交评价</el-button>
          </div>
        </div>
      </div>
      
      <div v-if="getUserId()">
      <!-- 未购买商品提示 -->
        <div class="comment-not-allowed" v-if="!canComment && !commentLoading">
          <el-alert
            title="您尚未购买此商品，购买后才能发表评价"
            type="info"
            :closable="false"
            center
            show-icon
          />
        </div>
      </div>
      <div v-loading="commentLoading">
        <div v-if="comments.length === 0" class="no-comments">暂无评价</div>
        <div v-else>
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <el-avatar :size="36" :src="comment.avatar" />
              <div class="comment-user">
                <span class="username">{{ comment.username }}</span>
                <StarRating :score="comment.score" />
              </div>
              <span class="comment-time">{{ comment.time }}</span>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
            <!-- 评论图片展示 -->
            <div class="comment-images" v-if="comment.images && comment.images.length > 0">
              <el-image
                v-for="(img, index) in comment.images"
                :key="index"
                :src="img"
                :preview-src-list="comment.images"
                fit="cover"
                class="comment-image"
              />
            </div>
          </div>
          
          <!-- 评论分页 -->
          <div class="comment-pagination" v-if="commentTotal > 0">
            <el-pagination
              v-model:current-page="commentPage"
              v-model:page-size="commentPageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="commentTotal"
              :current-page="commentPage"
              :page-size="commentPageSize"
              @size-change="handleCommentSizeChange"
              @current-change="handleCommentPageChange"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 商品属性参数 -->
    <div class="goods-attributes-table">
      <h2 class="attributes-title">参数信息</h2>
      <div class="attributes-table">
        <div class="attributes-row" v-for="(row, idx) in groupedAttributes" :key="idx">
          <template v-for="(attr, i) in row" :key="attr.attrKey">
            <div class="attr-cell attr-key">{{ attr.attrKey }}</div>
            <div class="attr-cell attr-value">{{ safeParse(attr.attrValue) }}</div>
          </template>
          <!-- 如果这一行只有一个参数，补空格 -->
          <template v-if="row.length === 1">
            <div class="attr-cell"></div>
            <div class="attr-cell"></div>
          </template>
        </div>
      </div>
      <div v-if="groupedAttributes.length === 0" style="text-align:center;color:#aaa;padding:32px 0;">
        暂无参数信息
      </div>
    </div>
  </template>
</template>

<script setup>
import { getGoodsDetail, getAttribute } from '@/api/goods'
import { getShopCard } from '@/api/shop'
import { addToCart as addToCartApi } from '@/api/cart'
import { isGoodFavorite, addFavorite, cancelFavorite } from '@/api/favorite'
import { getCommentsBySpuId, addComment } from '@/api/comments'
import { checkUserCanComment } from '@/api/order'

import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import StarRating from '@/components/shop/StarRating.vue'
import { Plus } from '@element-plus/icons-vue'

const { score } = defineProps({
  score: {
    type: Number,
    required: true
  }
})

const route = useRoute()
const router = useRouter()
const goodsId = Number(route.query.id) // 商品ID (spuId)
const orderIdFromQuery = route.query.orderId ? Number(route.query.orderId) : null // 从URL获取订单ID
const shopId = ref(null)
const quantity = ref(1)
const currentImage = ref('')
const spu = ref({})
const sku = ref({})
const specTemplate = ref({})
const selectedSpecs = ref({}) // { 存储: '64GB', 颜色: '粉色' }
const skuList = ref([]) // SKU列表
const specOptions = ref({}) // { 存储: ['64GB', '128GB'], 颜色: ['粉色', '黑色'] }
const shopInfo = ref({}) // 添加店铺信息响应式变量
const comments = ref([])
const commentPage = ref(1)
const commentPageSize = ref(10)
const commentLoading = ref(false)

// 评论相关状态
const canComment = ref(false)
const orderId = ref(null)
const commentForm = ref({
  rating: 5,
  content: '',
  imageUrls: []
})
const uploadedImages = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const submitLoading = ref(false)

const attributes = ref([])
const commentTotal = ref(0) // 评论总数
const skuSpecs = ref([])
const isFavorite = ref(false)
const pageLoading = ref(true) // 添加页面加载状态
const brandName = ref('') // 添加品牌名称
const shopName = ref('') // 添加店铺名称
const sales = ref(0) // 添加销量
const promotionInfo = ref('') // 添加促销信息

// 选择规格
const selectSpec = (key, option) => {
  selectedSpecs.value[key] = option
  updateSelectedSku()
}

// 更新选中的SKU
const updateSelectedSku = () => {
  // 找到与当前所有选中规格完全匹配的skua
  const sku = skuList.value.find(item => {
    const specs = JSON.parse(item.specs)
    return Object.entries(selectedSpecs.value).every(
      ([k, v]) => specs[k] === v
    )
  })
  if (sku) {
    currentImage.value = sku.mainImage
    spu.value.price = sku.price
    spu.value.stock = sku.stock
    // 你可以根据需要赋值更多字段
  }
}

const generateSpecOptions = (skuList) => {
  const options = {}
  skuList.forEach(sku => {
    const specs = JSON.parse(sku.specs)
    Object.entries(specs).forEach(([key, value]) => {
      if (!options[key]) options[key] = new Set()
      options[key].add(value)
    })
  })
  // 转成数组
  Object.keys(options).forEach(key => {
    options[key] = Array.from(options[key])
  })
  return options
}

// 加载评论数据
const loadComments = async () => {
  try {
    commentLoading.value = true
    // 根据响应拦截器，如果请求成功，会直接返回 res.data
    const data = await getCommentsBySpuId(goodsId, commentPage.value, commentPageSize.value)
    
    // 处理分页信息
    commentTotal.value = data?.total || 0
    
    // 处理评论数据
    if (data?.records && Array.isArray(data.records)) {
      comments.value = data.records.map(comment => ({
        id: comment.id,
        username: comment.userName || '匿名用户',
        avatar: comment.userIcon || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        score: comment.rating || 5,
        content: comment.content || '',
        time: comment.createdAt ? formatCommentTime(comment.createdAt) : '未知时间',
        images: Array.isArray(comment.imageUrls) ? comment.imageUrls : []
      }))
    } else {
      comments.value = []
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    comments.value = []
    commentTotal.value = 0
    // 如果是未登录错误，可能需要跳转到登录页面
    if (error.message && error.message.includes('未登录')) {
      ElMessage.warning('请登录后查看评论')
    }
  } finally {
    commentLoading.value = false
  }
}

// 检查用户是否可以评论
const checkCanComment = async () => {
  try {
    // 首先检查是否已经从URL获取了订单ID
    if (orderIdFromQuery) {
      orderId.value = orderIdFromQuery
      canComment.value = true
      return
    }
    
    // 判断用户是否登录
    const uid = getUserId()
    if (!uid) {
      canComment.value = false
      return
    }
    
    // 如果没有orderId参数，调用API检查用户是否购买过商品
    // 根据响应拦截器，如果请求成功，会直接返回处理后的数据
    const result = await checkUserCanComment(goodsId)
    
    // 接口返回的是订单ID，如果有值则表示用户购买过此商品
    if (result) {
      orderId.value = result
      canComment.value = true
    } else {
      orderId.value = null
      canComment.value = false
    }
  } catch (error) {
    console.error('检查评论权限失败:', error)
    orderId.value = null
    canComment.value = false
    
    // 如果是未登录错误，不需要提示，因为未登录用户本来就不能评论
    if (error.message && !error.message.includes('未登录')) {
      ElMessage.error('检查评论权限失败')
    }
  }
}

// 格式化评论时间
const formatCommentTime = (timestamp) => {
  if (!timestamp) return '未知时间'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 图片上传相关方法
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = (file) => {
  const index = uploadedImages.value.findIndex(img => img === file.url)
  if (index !== -1) {
    uploadedImages.value.splice(index, 1)
    commentForm.value.imageUrls = uploadedImages.value
  }
}

const handleUploadSuccess = (response) => {
  if (response && response.url) {
    uploadedImages.value.push(response.url)
    commentForm.value.imageUrls = uploadedImages.value
  }
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交评论
const submitComment = async () => {
  //判断是否登录
  const uid = getUserId()
  if (!uid) {
    router.push({
      path: '/login',
      query: {
        redirect: route.fullPath
      }
    })
    return
  }

  if (!commentForm.value.content.trim()) {
    ElMessage.warning('请输入评价内容')
    return
  }

  try {
    submitLoading.value = true
    
    const commentData = {
      spuId: goodsId,
      orderId: orderId.value, // 从checkUserCanComment获取的订单ID
      content: commentForm.value.content,
      rating: commentForm.value.rating,
      imageUrls: JSON.stringify(uploadedImages.value)
    }
    
    // 根据响应拦截器，如果请求成功，会直接返回处理后的数据
    // 如果失败会抛出异常
    const result = await addComment(commentData)
    
    // 处理成功响应
    ElMessage.success('评价提交成功')
    
    // 重置表单
    commentForm.value = {
      rating: 5,
      content: '',
      imageUrls: []
    }
    uploadedImages.value = []
    
    // 重新加载评论列表
    commentPage.value = 1
    await loadComments()
    
    // 如果是从订单详情页跳转过来的，可以返回订单页或者提示用户
    if (orderIdFromQuery) {
      // 滚动到评论区
      nextTick(() => {
        document.querySelector('.goods-comments').scrollIntoView({ behavior: 'smooth' })
      })
      
      // 可以添加一个提示，让用户知道评价已成功并可以返回订单页
      ElMessage({
        message: '评价成功！您可以返回订单页面查看',
        type: 'success',
        duration: 5000
      })
    }
    
  } catch (error) {
    console.error('提交评价失败:', error)
    
    // 根据错误类型提供更具体的提示
    if (error.message && error.message.includes('未登录')) {
      ElMessage.warning('登录已过期，请重新登录')
      // 可能需要跳转到登录页
      router.push({
        path: '/login',
        query: { redirect: route.fullPath }
      })
    } else if (error.message && error.message.includes('未购买')) {
      ElMessage.warning('您尚未购买此商品，无法评价')
    } else {
      ElMessage.error(error.message || '提交评价失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 加载所有数据
const loadAllData = async () => {
  try {
    pageLoading.value = true
    
    // 使用Promise.all同时发起多个请求
    const [goodsRes, attributeRes] = await Promise.all([
      // 获取商品详情
      getGoodsDetail(goodsId).catch(error => {
        console.error('获取商品详情失败:', error)
        ElMessage.error('获取商品详情失败，请刷新重试')
        return null
      }),
      
      // 获取商品属性
      getAttribute(goodsId).catch(error => {
        console.error('获取商品属性失败:', error)
        return { attributes: [], skuSpecs: [] }
      })
    ])
    
    // 处理商品详情数据
    if (goodsRes) {
      shopId.value = goodsRes.shopId
      
      // 映射SPU数据
      spu.value = {
        id: goodsRes.id,
        price: goodsRes.price,
        title: goodsRes.title,
        description: goodsRes.description,
        mainImage: goodsRes.mainImage,
        subImages: goodsRes.subImages || [],
        detail_html: goodsRes.detailsHtml,
        shopId: goodsRes.shopId
      }
      
      // 设置品牌和店铺名称
      brandName.value = goodsRes.brandName || '未知品牌'
      shopName.value = goodsRes.shopName || '未知店铺'
      sales.value = goodsRes.sales || 0
      promotionInfo.value = goodsRes.promotionInfo || ''
      
      // 映射SKU数据（默认使用第一个SKU）
      if (goodsRes.skuList && goodsRes.skuList.length > 0) {
        sku.value = {
          id: goodsRes.skuList[0].id,
          price: goodsRes.skuList[0].price,
          cost_price: goodsRes.skuList[0].costPrice,
          stock: goodsRes.skuList[0].stock,
          specs: JSON.parse(goodsRes.skuList[0].specs)
        }
        // 设置当前图片
        currentImage.value = goodsRes.skuList[0].mainImage || goodsRes.mainImage
      }
      
      //sku规格列表
      skuList.value = goodsRes.skuList
      // 映射规格模板
      specTemplate.value = goodsRes.specsTemplate ? JSON.parse(goodsRes.specsTemplate) : {}
      specOptions.value = generateSpecOptions(skuList.value)
      // 默认选中第一个sku的所有规格
      if (skuList.value.length > 0) {
        const firstSpecs = JSON.parse(skuList.value[0].specs)
        Object.keys(firstSpecs).forEach(key => {
          selectedSpecs.value[key] = firstSpecs[key]
        })
        updateSelectedSku()
      }
      
      // 获取店铺信息
      if (shopId.value) {
        try {
          const shopRes = await getShopCard(shopId.value)
          shopInfo.value = shopRes
        } catch (error) {
          console.error('获取商铺卡片失败:', error)
        }
      }
    } else {
      ElMessage.error('获取商品信息失败')
    }
    
    // 处理属性数据
    if (attributeRes) {
      attributes.value = attributeRes.attributes || []
      skuSpecs.value = attributeRes.skuSpecs || []
    }
    
    // 查询是否已收藏
    try {
      if (getUserId()) {
        const favoriteRes = await isGoodFavorite(goodsId)
        isFavorite.value = !!favoriteRes
      }
    } catch (error) {
      isFavorite.value = false
    }
    
    // 加载评论数据
    await loadComments()
    
    // 检查用户是否可以评论
    await checkCanComment()
    
    // 如果有scrollToComment参数或者从订单页跳转过来，滚动到评论区
    if (route.query.scrollToComment || orderIdFromQuery) {
      nextTick(() => {
        const commentsSection = document.querySelector('.goods-comments')
        if (commentsSection) {
          commentsSection.scrollIntoView({ behavior: 'smooth' })
        }
      })
    }
    
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请刷新重试')
  } finally {
    pageLoading.value = false
  }
}

onMounted(() => {
  loadAllData()
})

// 数量相关方法
const validateQuantity = () => {
  let val = parseInt(quantity.value)
  if (isNaN(val) || val < 1) {
    quantity.value = 1
  } else if (val > 10) {//数量最多为10
    quantity.value = 10
  }
}

const getStarClass = (idx) => {
  if (score >= idx + 1) return 'full'
  if (score >= idx + 0.5) return 'half'
  return 'empty'
}

const groupedAttributes = computed(() => {
  const arr = []
  for (let i = 0; i < attributes.value.length; i += 2) {
    arr.push(attributes.value.slice(i, i + 2))
  }
  return arr
})

function safeParse(val) {
  try {
    return JSON.parse(val)
  } catch {
    return val
  }
}

// 处理评论分页大小变化
const handleCommentSizeChange = (size) => {
  commentPageSize.value = size
  commentPage.value = 1
  loadComments()
}

// 处理评论页码变化
const handleCommentPageChange = (page) => {
  commentPage.value = page
  loadComments()
  
  // 滚动到评论区顶部，提升用户体验
  nextTick(() => {
    document.querySelector('.goods-comments').scrollIntoView({ behavior: 'smooth' })
  })
}

// 获取用户ID
const getUserId = () => {
  const idCookie = document.cookie.split(';').find(item => item.trim().startsWith('id='))
  if (!idCookie) return null
  const id = idCookie.split('=')[1].trim()
  return id ? parseInt(id) : null
}

// 加入购物车方法
const handleAddToCart = async () => {
  const uid = getUserId()
  if (!uid) {
    // 未登录时跳转到登录页面
    router.push({
      path: '/login',
      query: {
        redirect: route.fullPath
      }
    })
    return
  }

  // 验证是否选择了所有规格
  const allSpecsSelected = Object.keys(specOptions.value).every(
    key => selectedSpecs.value[key]
  )
  if (!allSpecsSelected) {
    ElMessage.warning('请选择商品规格')
    return
  }

  // 找到对应的SKU
  const selectedSku = skuList.value.find(item => {
    const specs = JSON.parse(item.specs)
    return Object.entries(selectedSpecs.value).every(
      ([k, v]) => specs[k] === v
    )
  })

  if (!selectedSku) {
    ElMessage.error('商品规格选择有误')
    return
  }

  try {
    await addToCartApi(selectedSku.id, quantity.value)
    ElMessage.success('成功加入购物车')
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error(error.message || '加入购物车失败')
  }
}

const buyNow = async () => {
  const uid = getUserId()
  if (!uid) {
    router.push({
      path: '/login',
      query: {
        redirect: route.fullPath
      }
    })
    return
  }

  // 验证是否选择了所有规格
  const allSpecsSelected = Object.keys(specOptions.value).every(
    key => selectedSpecs.value[key]
  )
  if (!allSpecsSelected) {
    ElMessage.warning('请选择商品规格')
    return
  }

  // 找到对应的SKU
  const selectedSku = skuList.value.find(item => {
    const specs = JSON.parse(item.specs)
    return Object.entries(selectedSpecs.value).every(
      ([k, v]) => specs[k] === v
    )
  })

  if (!selectedSku) {
    ElMessage.error('商品规格选择有误')
    return
  }

  try {
    // 1. 添加到购物车
    const cartResponse = await addToCartApi(selectedSku.id, quantity.value)
    // 2. 跳转到购物车，并传递刚添加商品的购物车项ID
    router.push({
      path: '/cart',
      query: {
        highlight: cartResponse?.id || selectedSku.id, // 优先使用返回的购物车项ID
        _t: Date.now() // 添加时间戳防止缓存问题
      }
    })
  } catch (error) {
    console.error('立即购买失败:', error)
    ElMessage.error(error.message || '立即购买失败')
  }
}

const handleFavorite = async () => {
  if (!getUserId()) {
    router.push({
      path: '/login',
      query: { redirect: route.fullPath }
    })
    return
  }
  try {
    if (isFavorite.value) {
      await cancelFavorite(goodsId)
      ElMessage.success('已取消收藏')
      isFavorite.value = false
    } else {
      await addFavorite(goodsId)
      ElMessage.success('收藏成功')
      isFavorite.value = true
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  }
}
</script>

<style scoped>
.goods-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  display: flex;
  gap: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 全屏加载样式 */
.full-page-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 左侧图片区样式 */
.goods-images {
  width: 480px;
  flex-shrink: 0;
}

.main-image {
  width: 100%;
  height: 480px;
  object-fit: contain;
  border-radius: 8px;
  margin-bottom: 10px;
  border: 1px solid #f0f0f0;
}

.sub-images {
  display: flex;
  gap: 10px;
  overflow-x: auto;
  padding: 5px 0;
}

.sub-images img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.sub-images img.active {
  border-color: #ff4d4f;
}

/* 右侧区域容器 */
.goods-right-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 商品信息区样式 */
.goods-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.title {
  font-size: 24px;
  color: #333;
  margin: 0;
  line-height: 1.4;
}

.brand-shop {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.price {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
}

.current-price {
  font-size: 32px;
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 10px;
}

.origin-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.promotion {
  background: #fff2f0;
  color: #ff4d4f;
  padding: 10px 15px;
  border-radius: 4px;
  font-size: 14px;
}

.sales-stock {
  display: flex;
  gap: 30px;
  color: #666;
  font-size: 14px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

/* 规格选择区域样式 */
.specs {
  margin: 20px 0;
}

.spec-row {
  margin-bottom: 15px;
}

.spec-label {
  color: #666;
  display: block;
  margin-bottom: 8px;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.spec-option {
  padding: 6px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.spec-option:hover {
  border-color: #ff4d4f;
  color: #ff4d4f;
}

.spec-option.selected {
  background: #ff4d4f;
  color: #fff;
  border-color: #ff4d4f;
}

.quantity {
  margin: 20px 0;
  display: flex;
  align-items: center;
  gap: 15px;
}

.quantity input {
  width: 80px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
}

/* 购买按钮区域 */
.buy-btns {
  display: flex;
  gap: 20px;
  margin: 30px 0;
}

.buy-btns button {
  flex: 1;
  height: 50px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.3s;
}

.buy-btns button:first-child {
  background: #fff2f0;
  border: 1px solid #ff4d4f;
  color: #ff4d4f;
}

.buy-btns button:first-child:hover {
  background: #ffd4d4;
}

.buy-btns button.buy-now {
  background: #ff4d4f;
  color: #fff;
}

.buy-btns button.buy-now:hover {
  background: #ff7875;
}

.favorite-btn {
  background: #fffbe6;
  color: #faad14;
  border: 1px solid #ffe58f;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}
.favorite-btn.active {
  background: #ffe58f;
  color: #d48806;
  border-color: #ffd666;
}
.favorite-btn i {
  font-size: 18px;
}

/* 服务承诺区域 */
.service {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
  border-top: 1px solid #f0f0f0;
  color: #666;
  font-size: 14px;
}

.service span {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 商品详情标签页 */
.goods-detail-tabs {
  max-width: 1200px;
  margin: 20px auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  height: 60px;
  line-height: 60px;
  padding: 0 30px;
}

:deep(.el-tabs__item.is-active) {
  color: #ff4d4f;
  font-weight: bold;
}

:deep(.el-tabs__active-bar) {
  background-color: #ff4d4f;
  height: 3px;
}

:deep(.el-tab-pane) {
  padding: 30px;
}
/* 数量选择器样式 */
.quantity {
  display: flex;
  align-items: center;
  gap: 20px;
  margin: 20px 0;
}

.quantity span {
  color: #666;
}

.quantity-input {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.quantity-btn {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border: none;
  cursor: pointer;
  font-size: 18px;
  color: #666;
  transition: all 0.3s;
}

.quantity-btn:hover:not(:disabled) {
  background: #e0e0e0;
}

.quantity-btn:disabled {
  cursor: not-allowed;
  color: #ccc;
}

.quantity-input input {
  width: 50px;
  height: 28px;
  border: none;
  border-left: 1px solid #e0e0e0;
  border-right: 1px solid #e0e0e0;
  text-align: center;
  font-size: 14px;
  color: #333;
  -moz-appearance: textfield;
}

.quantity-input input::-webkit-outer-spin-button,
.quantity-input input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 商铺卡片样式 */
.shop-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.shop-header-left {
  flex: 1;
}

.shop-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.shop-image {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #f0f0f0;
}

.shop-detail {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.shop-name {
  font-size: 18px;
  color: #333;
  margin: 0;
  font-weight: 600;
}

.shop-score {
  display: flex;
  align-items: center;
  gap: 5px;
}

.score {
  color: #ff4d4f;
  font-size: 14px;
}

.shop-header-right {
  display: flex;
  gap: 20px;
}

.contact-service,
.enter-shop {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 15px;
  border-radius: 4px;
  text-decoration: none;
  transition: all 0.3s ease;
}

.contact-service {
  color: #666;
  background: #f5f5f5;
}

.enter-shop {
  color: #fff;
  background: #ff4d4f;
}

.contact-service:hover {
  background: #e8e8e8;
}

.enter-shop:hover {
  background: #ff7875;
}

.contact-service i,
.enter-shop i {
  font-size: 16px;
}

.goods-comments {
  max-width: 1200px;
  margin: 30px auto 0 auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  padding: 30px 40px;
}

.comments-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 24px;
}

.no-comments {
  color: #888;
  text-align: center;
  padding: 30px 0;
}

.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 18px 0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 8px;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-weight: 500;
  color: #333;
}

.comment-time {
  margin-left: auto;
  color: #bbb;
  font-size: 13px;
}

.comment-content {
  color: #444;
  font-size: 15px;
  line-height: 1.7;
  padding-left: 52px;
  word-break: break-word;
  white-space: pre-wrap;
}

.enter-shop.disabled {
  background: #ccc;
  cursor: not-allowed;
  pointer-events: none;
}

.enter-shop.disabled:hover {
  background: #ccc;
}

/* 商品属性参数样式 */
.goods-attributes-table {
  max-width: 900px;
  margin: 32px auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  padding: 32px 40px;
}

.attributes-title {
  font-size: 20px;
  font-weight: bold;
  color: #222;
  margin-bottom: 24px;
}

.attributes-table {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 0;
}

.attributes-row {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  min-height: 44px;
}

.attr-cell {
  flex: 1;
  padding: 10px 12px;
  font-size: 15px;
  color: #333;
  background: #fff;
  word-break: break-all;
  display: flex;
  align-items: center;
}

.attr-key {
  background: #f7fafd;
  color: #666;
  font-weight: 500;
  min-width: 120px;
}

.attr-value {
  background: #fff;
  color: #222;
}

/* 评论分页样式 */
.comment-pagination {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

/* 评论表单样式 */
.comment-form-container {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  border: 1px solid #eee;
}

.comment-form-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.comment-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.rating-row, .content-row, .image-upload-row {
  display: flex;
  align-items: flex-start;
}

.form-label {
  width: 100px;
  color: #666;
  line-height: 32px;
}

.content-row .el-input {
  flex: 1;
}

.comment-submit {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.comment-not-allowed {
  margin-bottom: 30px;
}

/* 评论图片样式 */
.comment-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
  padding-left: 52px;
}

.comment-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}
</style>
